package com.version2_0.service.implement;

import com.alibaba.fastjson.JSONArray;
import com.util.format.ReevesMap;
import com.util.format.TimeFormat;
import com.util.page.GetPageModel;
import com.util.property.Properties;
import com.version2_0.dao.PageDao2_0;
import com.version2_0.service.PageService2_0;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by reeveslee on 16/6/7.
 */
@Service
public class PageServiceImpl2_0 implements PageService2_0 {
    private static final Logger LOGGER = Logger.getLogger(PageServiceImpl2_0.class);

    @Autowired
    private PageDao2_0 pageDao20;


    @Override
    public String pages(int userId, int sectionId, long timestamp, int lastId) {
        ReevesMap reevesMap = new ReevesMap();
        List<Map<String, Object>> infoList = pageDao20.pages(sectionId, timestamp, lastId);

        if (infoList == null) {
            reevesMap.setCode(500);
            reevesMap.setInfo("No Information Found.");
        } else {
            List<Map<String, Object>> result = new ArrayList<>();
            for (Map<String, Object> item : infoList) {
                int type = (int) item.get("type");
                int subId = (int) item.get("subId");
                int id = (int) ((long) item.get("id"));

                Map<String, Object> map = pageDao20.getSectionInfo(type, subId);
                map.put("id", id);
                map.put("type", type);
                if (type == 6 || type == 8 || type == 1 || type == 2) {
                    // 多图样式信息,titleImage是图数组
                    map.replace("titleImage", JSONArray.parse((String) map.get("titleImage")));
                }

                if (type == 3) {
                    // 投票信息检查用户是否已投票
                    map.put("hasVoted", pageDao20.checkVote(userId, (int) map.get("id")));

                    int one = (int) map.get("oneSupport");
                    int second = (int) map.get("secondSupport");

                    map.put("oneResult", new DecimalFormat("#.00").format(one * 1.0 / (one + second)));
                    map.put("secondResult", new DecimalFormat("#.00").format(second * 1.0 / (one + second)));
                }

                result.add(map);
            }
            reevesMap.put("result", result);
        }
        return reevesMap.toJsonString();
    }

    @Override
    public String content(int pageId) {
        Map<String, Object> pageMap = pageDao20.page(pageId);

        if (pageMap == null) {
            // 转到404页面
            return null;
        } else {
            // String image = (String) pageMap.get("titleImage") + "@!pageStyle";
            String title = (String) pageMap.get("title");
            String source = (String) pageMap.get("source");
            String pageContent = (String) pageMap.get("pageContent");
            int readNumber = (int) pageMap.get("readNumber");
            String date = new SimpleDateFormat("yyyy-MM-dd").format((Date) pageMap.get("time"));

            String htmlString = "";

            String pageModelStr = GetPageModel.getPageModelStr(Properties.Page_TestModelURL);
            htmlString = pageModelStr;
            htmlString = htmlString.replace("{kuibu_pageTitle}", title);
            htmlString = htmlString.replace("{kuibu_pageReadNumber}", String.valueOf(readNumber));
            htmlString = htmlString.replace("{kuibu_pageFrom}", source);
            htmlString = htmlString.replace("{kuibu_pageContent}", pageContent);
            htmlString = htmlString.replace("{kuibu_pageDate}", date);

            return htmlString;
        }
    }

    @Override
    public String info(int pageId, int userId) {
        ReevesMap reevesMap = new ReevesMap();
        // 1. 文章标题图片
        //String titleImage = (pageDao20.page(pageId)).get("titleImage") + "@!style";
        String titleImage = (String) (pageDao20.page(pageId)).get("titleImage");

        // 2. 推荐文章
        List<Map<String, Object>> recom = pageDao20.recoms(pageId);

        // 3. 评论数
        int comNum = pageDao20.pageComNumber(pageId);

        // 4. 是否收藏
        boolean collect = pageDao20.hasCollect(pageId, userId);

        reevesMap.put("titleImage", titleImage);
        reevesMap.put("recomPages", recom);
        reevesMap.put("comment", comNum);
        reevesMap.put("collect", collect);
        return reevesMap.toJsonString();
    }

    @Override
    public String comment(int pageId, int userId, int lastId) {
        List<Map<String, Object>> commentList = pageDao20.comment(pageId, lastId);
        ReevesMap reevesMap = new ReevesMap();
        if (commentList != null) {
            for (Map<String, Object> item : commentList) {
                item.put("hasPraised", pageDao20.hasPraised((int) (long) item.get("id"), userId));
                List<Map<String, Object>> replys = pageDao20.reply((int) (long) item.get("id"));
                for (Map<String, Object> map : replys) {
                    map.replace("time", TimeFormat.convertTimeToFormat(((Date) map.get("time")).getTime() / 1000));
                }
                item.put("replys", replys);
                item.replace("time", TimeFormat.convertTimeToFormat(((Date) item.get("time")).getTime() / 1000));
                item.replace("images", JSONArray.parse((String) item.get("images")));
            }

            reevesMap.put("comments", commentList);
        }

        return reevesMap.toJsonString();
    }


    /**
     * 发表文章评论
     *
     * @param userId
     * @param pageId
     * @param text
     * @param images
     * @return
     */
    @Override
    public String addComment(int userId, int pageId, String text, JSONArray images) {
        ReevesMap reevesMap = new ReevesMap();

        boolean result = pageDao20.addComment(userId, pageId, text, images.toJSONString());
        if (!result) {
            reevesMap.setCode(500);
            reevesMap.setInfo("error occurred during add user comment to database.");
        }
        return reevesMap.toJsonString();
    }

    /**
     * 删除文章评论
     *
     * @param userId
     * @param commentId
     * @return
     */
    @Override
    public String delComment(int userId, int commentId) {
        ReevesMap reevesMap = new ReevesMap();

        boolean result = pageDao20.delComment(userId, commentId);
        if (!result) {
            reevesMap.setCode(500);
            reevesMap.setInfo("error occurred during delete user comment to database.");
        }
        return reevesMap.toJsonString();
    }

    @Override
    public String voteChose(int userId, int voteInfoId, int chose) {
        Map<String, Object> voteCurrInfo = pageDao20.voteChose(userId, voteInfoId, chose);
        ReevesMap reevesMap = new ReevesMap();

        if (voteCurrInfo == null) {
            reevesMap.setCode(500);
            reevesMap.setInfo("error occurred during insert vote record or update vote result,please call reeves.");
        } else {
            int one = (int) voteCurrInfo.get("oneSupport");
            int second = (int) voteCurrInfo.get("secondSupport");

            reevesMap.put("oneResult", new DecimalFormat("#.00").format(one * 1.0 / (one + second)));
            reevesMap.put("secondResult", new DecimalFormat("#.00").format(second * 1.0 / (one + second)));
        }

        return reevesMap.toJsonString();
    }

    @Override
    public String history(int lastId) {
        List<Map<String, Object>> historyList = pageDao20.history(lastId);
        ReevesMap reevesMap = new ReevesMap();

        for (Map<String, Object> item : historyList) {
            item.replace("time", TimeFormat.convertTimeToFormat(((Date) item.get("time")).getTime() / 1000));
            item.replace("titleImage", JSONArray.parse((String) item.get("titleImage")));
        }

        reevesMap.put("history", historyList);
        return reevesMap.toJsonString();
    }

    @Override
    public String video(int lastId) {
        List<Map<String, Object>> videoList = pageDao20.video(lastId);
        ReevesMap reevesMap = new ReevesMap();

        for (Map<String, Object> item : videoList) {
            item.replace("time", TimeFormat.convertTimeToFormat(((Date) item.get("time")).getTime() / 1000));
        }

        reevesMap.put("video", videoList);
        return reevesMap.toJsonString();
    }

    @Override
    public String vote(int userId, int lastId) {
        // {"voteList":[{"id","title",""}]}
        List<Map<String, Object>> voteList = pageDao20.vote(lastId);
        ReevesMap reevesMap = new ReevesMap();
        for (Map<String, Object> map : voteList) {
            map.put("hasVoted", pageDao20.checkVote(userId, (int)(long) map.get("id")));

            int one = (int) map.get("oneSupport");
            int second = (int) map.get("secondSupport");

            map.put("oneResult", new DecimalFormat("#.00").format(one * 1.0 / (one + second)));
            map.put("secondResult", new DecimalFormat("#.00").format(second * 1.0 / (one + second)));
        }

        reevesMap.put("voteList", voteList);
        return reevesMap.toJsonString();
    }
}
